Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

A Comprehensive Description of COUNT in SQL Server

Leave a Comment

Counting rows is a frequent task that many SQL developers come into when working with SQL Server. It is essential to comprehend the distinctions between DISTINCT COUNT, COUNT(1), and COUNT(*) when crafting effective and optimized queries. We will delve further into these SQL counting techniques in this post, comprehend their subtleties, and look at performance issues.

COUNT(*)

The COUNT(*) function is used to count all rows in a table or the result set of a query. It includes NULL values and duplicates. This is the most commonly used COUNT function due to its simplicity and broad applicability.

USE [AdventureWorks2022]
GO

SELECT COUNT(*) AS TotalRows
FROM [HumanResources].[Employee] WITH(NOLOCK)
COUNT(1)

The COUNT(1) function operates similarly to COUNT(*) but counts the number of rows by evaluating the constant value 1 for each row. This can sometimes be seen as a trick to improve performance, although in most cases, there is no significant difference.

USE [AdventureWorks2022]
GO

SELECT COUNT(1) AS TotalRows
FROM [HumanResources].[Employee] WITH(NOLOCK)
COUNT(column_name)

The COUNT(column_name) function counts the number of non-NULL values in a specified column. This is useful when you need to count entries in a column while ignoring NULL values.

USE [AdventureWorks2022]
GO

SELECT COUNT(BusinessEntityID) AS TotalRows
FROM [HumanResources].[Employee] WITH(NOLOCK)
COUNT(DISTINCT column_name)

The COUNT(DISTINCT column_name) function counts the number of distinct non-NULL values in a specified column. This is useful for identifying the number of unique entries in a dataset.

USE [AdventureWorks2022]
GO

SELECT COUNT(LoginID) AS TotalRows
FROM [HumanResources].[Employee] WITH(NOLOCK)
SQL

Performance Considerations
 

COUNT(*) COUNT(1) COUNT(column_name) COUNT(DISTINCT column_name)
The COUNT(*) function is efficient because it does not need to evaluate any specific column values. Instead, it counts rows at the storage level. SQL Server optimizes this operation by utilizing the table's metadata, making it faster than counting specific columns, especially when those columns are large or contain complex data types. From a performance perspective, COUNT(1) and COUNT(*) are typically equivalent. The SQL Server optimizer treats them the same way and generates similar execution plans. Therefore, choosing between COUNT(1) and COUNT(*) is mostly a matter of preference or coding standards rather than performance. COUNT(column_name) can be less efficient than COUNT(*) or COUNT(1) because it requires evaluating each value in the specified column to determine if it is NULL. However, if the column is indexed, SQL Server can leverage the index to improve performance. It is important to consider the size and complexity of the column when using this function. COUNT(DISTINCT column_name) can be significantly more resource-intensive than COUNT(*) or COUNT(column_name) because it requires sorting and deduplicating the values in the specified column. The performance impact is more pronounced for large datasets or columns with many distinct values. Using indexes on the column can help, but it may not completely mitigate the overhead.

Use Cases

COUNT(*) COUNT(1) COUNT(column_name) COUNT(DISTINCT column_name)
Counting all rows in a table or result set Similar to COUNT(*), often used interchangeably Counting non-NULL values in a specific column Counting unique non-NULL values in a specific column

Advanced Scenarios

  • Counting with Conditions: Sometimes, you may need to count rows based on specific conditions. This can be achieved using the CASE statement within the COUNT function.
    USE [AdventureWorks2022]
    GO
    
    SELECT
        COUNT(CASE WHEN OrganizationLevel = 1 THEN 1 END) AS VicePresident,
        COUNT(CASE WHEN OrganizationLevel = 2 THEN 1 END) AS EngineeringManager
    FROM [HumanResources].[Employee] WITH(NOLOCK)
  • Combining COUNT with Other Aggregate Functions: You can combine COUNT with other aggregate functions like SUM, AVG, MAX, and MIN to derive more complex insights.
    USE [AdventureWorks2022]
    GO
    
    SELECT
        COUNT(*) AS TotalEmployees,
        AVG(Rate) AS AverageSalary,
        MAX(Rate) AS HighestSalary,
        MIN(Rate) AS LowestSalary
    FROM [HumanResources].[EmployeePayHistory] WITH(NOLOCK)
  • Conclusion

    Understanding the differences between COUNT(*), COUNT(1), COUNT(column_name), and COUNT(DISTINCT column_name) is crucial for SQL developers, data engineers, and DBAs. Each function serves specific purposes and has unique performance characteristics. By selecting the appropriate COUNT function and optimizing your queries, you can efficiently derive insights from your data and ensure optimal performance in SQL Server.

    SQL Server 2022 Recommendation

    HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest SQL Server 2022 Hosting. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2012 R2, SQL Server 2014, ASP.NET 4.5.2, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
     
    https://hostforlifeasp.net/
    Read More

    ASP.NET Tutorial: Use of Action Delegate in C# in Detail

    Leave a Comment

    The Action delegate type in C# represents a method that can be called, but as its return type is void, it does not produce a value. It can take in one or more parameters as input.



    Action exists in the System namespace and can be accessed in multiple overloads to support varying numbers of parameters. It's commonly used to create event handlers, callbacks, and functions to pass as arguments.

    Action Syntax
    • No Parameters: An Action can be defined as a method that does not accept any parameters and returns no value.
      Action myAction = () => Console.WriteLine("Hello, World!");
      myAction();  // Output: Hello, World!
    One or More Parameters: It is possible to create an Action that accepts one or more parameters while still returning no value.
    Action<string> greetAction = (name) => Console.WriteLine($"Hello, {name}!");
    greetAction("Alice");  // Output: Hello, Alice!
    
    Action<int, int> addAction = (x, y) => Console.WriteLine(x + y);
    addAction(5, 10);  // Output: 15

    Key Features

    • Absence of Return Value: In contrast to Func<T>, the Action delegate does not yield a return value; it consistently returns void.
    • Capability for Multiple Parameters: Action<T1, T2, ..., T16> allows for the definition of a delegate that can accept as many as 16 parameters.
    • Utilization of Anonymous Methods and Lambda Expressions: Action is frequently employed alongside lambda expressions or anonymous methods, promoting more succinct code.
    • Application in Event Handlers: Action proves beneficial when it is necessary to transfer methods (including parameters), particularly for callbacks or event-handling scenarios.

    Comparison with Func

    • Action<T>: Used when the method returns void and can take zero or more parameters.
    • Func<T, TResult>: Used when the method returns a value (TResult) and can take zero or more input parameters.

    For example

    • Func<int, int, int> could represent a method that takes two integers and returns an integer (like an addition function).
    • Action<int, int> could represent a method that takes two integers and performs an action (like printing the sum), but doesn't return a value.
    The appropriate context for utilizing Action
    1. Action is a delegate type used for methods that don't return values.
    2. It is useful for passing methods as parameters or defining callbacks.
    3. You can use Action for methods with zero to 16 input parameters.
    Examples of different types of Action delegates
    • Action with No Parameters
      Action action = () => Console.WriteLine("Action with no parameters!");
      action();
      // Output: Action with no parameters!
    Action with One Parameter
    Action<string> printMessage = (message) => Console.WriteLine(message);
    printMessage("Hello!");
    
    // Output: Hello!
    Action with Multiple Parameters
    Action<int, int> multiplyNumbers = (a, b) => Console.WriteLine(a * b);
    multiplyNumbers(4, 5);
    
    // Output: 20
    Passing Action as a Parameter to a Method: You can pass an Action as a method parameter to be executed later.
    public void PerformAction(Action action)
    {
        Console.WriteLine("Before action.");
        action();
        Console.WriteLine("After action.");
    }
    // Usage:
    PerformAction(() => Console.WriteLine("Executing action..."));
    // Output:
    // Before action.
    // Executing action...
    // After action
    Using Action with Event Handling
    public class Button
    {
        public Action Click { get; set; }
    
        public void OnClick()
        {
            Click?.Invoke(); // Invoke the Action if it's not null
        }
    }
    Button button = new Button();
    button.Click = () => Console.WriteLine("Button clicked!");
    button.OnClick();
    // Output: Button clicked!
    Execution of all previously mentioned actions within the application

    Step 1. I have developed a WPF user interface, as illustrated below. You may select any application type that aligns with your specific requirements.


    MainWindow.Xaml code

    <Window
        x:Class="ActionDelegateExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ActionDelegateExample"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="450"
        Width="800">
    
        <Grid>
            <StackPanel Orientation="Vertical">
                <Button
                    x:Name="BtnNoParameter"
                    Content="Action with no Parameter"
                    Click="BtnNoParameter_Click"
                    Height="40"
                    Margin="20"/>
    
                <Button
                    x:Name="BtnWithSingleParameter"
                    Content="Action with single Parameter"
                    Click="BtnWithSingleParameter_Click"
                    Height="40"
                    Margin="20"/>
    
                <Button
                    x:Name="BtnMultipleParameter"
                    Content="Action with multiple Parameter"
                    Click="BtnMultipleParameter_Click"
                    Height="40"
                    Margin="20"/>
    
                <Button
                    x:Name="BtnCallbackParameter"
                    Content="Action with call back"
                    Click="BtnCallbackParameter_Click"
                    Height="40"
                    Margin="20"/>
    
                <Button
                    x:Name="BtnCallEvenHandlingParameter"
                    Content="Action with CallEvenHandling"
                    Click="BtnCallEvenHandlingParameter_Click"
                    Height="40"
                    Margin="20"/>
            </StackPanel>
        </Grid>
    </Window>

    MainWindow.Xaml.cs code

    using System.Windows;
    
    namespace ActionDelegateExample
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                EventHandlerManager.OnEventRaised += EventHandlerManager_OnEventRaised;
            }
            private void EventHandlerManager_OnEventRaised()
            {
                MessageBox.Show("Event handled by Subscriber");
            }
            private void BtnNoParameter_Click(object sender, RoutedEventArgs e)
            {
                ActionMethods.NoParameterActionVariable();
            }
            private void BtnWithSingleParameter_Click(object sender, RoutedEventArgs e)
            {
                // Create a RequestMessage
                RequestMessageWithParameter message = new RequestMessageWithParameter
                {
                    Content = "This is a single parameter request."
                };
                ActionMethods.ActionWithOneParameter(message);
            }
            private void BtnMultipleParameter_Click(object sender, RoutedEventArgs e)
            {
                // Create a RequestMessage
                RequestMessageWithParameter message = new RequestMessageWithParameter
                {
                    Content = "This is a multiple parameter request."
                };
    
                // Invoke the Action with RequestMessage and an integer
                ActionMethods.ActionWithTwoParameters(message, 42);
            }
            private void BtnCallEvenHandlingParameter_Click(object sender, RoutedEventArgs e)
            {
                EventHandlerManager.RaiseOnEventRaised();
            }
            private void BtnCallbackParameter_Click(object sender, RoutedEventArgs e)
            {
                MessageHandler handler = new MessageHandler();
    
                // Define the callback action that will handle the RequestMessage after processing
                Action<RequestMessageWithParameter> callback = (request) =>
                {
                    MessageBox.Show($"Callback executed. Message content: {request.Content}");
                };
                // Call the method with a message and the callback action
                handler.ProcessRequest("Hello, this is a sample request!", callback);
            }
        }
    }

    Step 2. Establish a class titled "ActionMethods.cs" as illustrated below. It has been used to define action delegates

    using System.Windows;
    
    namespace ActionDelegateExample
    {
        public class ActionMethods
        {
            public static Action NoParameterActionVariable = () => NoParameterAction();
            private static void NoParameterAction()
            {
                MessageBox.Show("Action without parameters executed.");
            }
            // Action that accepts one parameter of type RequestMessage
            public static Action<RequestMessageWithParameter> ActionWithOneParameter = (request) =>
            {
                MessageBox.Show(request.Content);
            };
            // Action that accepts two parameters: RequestMessage and an integer
            public static Action<RequestMessageWithParameter, int> ActionWithTwoParameters = (request, count) =>
            {
                MessageBox.Show($"Action with two parameters executed. Message: {request.Content}, Count: {count}");
            };
        }
    }

    Step 3. Create a class named “MessageHandler.cs” as shown below. It will be used to manage an event of action type.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace ActionDelegateExample
    {
        public class MessageHandler
        {
            // Method that accepts an Action<RequestMessage> callback
            public void ProcessRequest(string messageContent, Action<RequestMessageWithParameter> callback)
            {
                // Create the RequestMessage
                RequestMessageWithParameter requestMessage = new RequestMessageWithParameter { Content = messageContent };
    
                // Simulate some processing
                Console.WriteLine("Processing the message...");
                System.Threading.Thread.Sleep(10000);
    
                // After processing, invoke the callback with the request message
                callback?.Invoke(requestMessage);
            }
        }
    }

    Step 4. Create a class by the name of ‘EventHandlerManager.cs” to handle the event.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace ActionDelegateExample
    {
        public class EventHandlerManager
        {
            public static event Action OnEventRaised;
            // Method to raise the event
            public static void RaiseOnEventRaised()
            {
                Action onEventRaised = OnEventRaised;
                if (onEventRaised != null)
                {
                    onEventRaised();
                }
            }
        }
    }
    A detailed description of the aforementioned code
    • RaiseOnEventRaised(): A static method that triggers the OnEventRaised event.
    • Action onEventRaised = OnEventRaised: Creates a local copy of the event delegate. This is done to avoid the potential issues of the event being null while invoking it.
    • if (onEventRaised != null): Checks if there are any subscribers to the event. If there are, it proceeds to invoke the event.
    • onEventRaised(): Invokes the event. This calls all methods that have subscribed to OnEventRaised.

    Step 6. The results obtained from testing are. 

    Action with No Parameters


    Action with One Parameter


     
    Action with Multiple Parameters


     
    Passing Action as a Parameter to a Method(Callback)


    Using Action with Event Handling

     


    Windows Hosting Recommendation

    HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
     
    https://hostforlifeasp.net/

     

    Read More

    Advanced Serilog Logging Methods in ASP.NET Core 8

    Leave a Comment

    Applications must be logged in order to monitor and analyze any problems or errors that may arise during development. Serilog is a well-liked and generally helpful tool for developers to log; it offers organized logging that makes it easier for developers to locate problems and errors fast.

    A diagnostic logging library for.NET applications is called Serilog. It offers a straightforward, adaptable, and effective method for logging errors, application events, and other data. Because Serilog is built for structured logging, it can log more than just text messages; it can log rich, structured data.

    Key Features of Serilog

    • Structured Logging: Serilog allows you to log structured data, which makes it easier to query and analyze logs. For example, you can log an object with multiple properties, and each property can be indexed and queried separately.
    • Sinks: Serilog supports various “sinks” that allow you to write logs to different storage systems, such as files, databases, consoles, and cloud services like Azure Application Insights, Elasticsearch, and more.
    • Configurable: Serilog is highly configurable. You can configure it to write logs to multiple sinks, filter logs by severity level, enrich logs with additional data, and more.
    • Performance: Serilog is designed to be performant and to minimize the impact on your application’s performance.
    • Integration: Serilog integrates well with other .NET libraries and frameworks, including ASP.NET Core, Entity Framework, and more.

    In this article, we will learn how we can use Serilog for logging.

    Now, let’s go.

    To follow Serilog implementation steps, you can use an existing project where you need to implement logging using Serilog or Create a new Asp.NET Core Web application. Now, let’s go for implementation. For this demo, I am using the ASP.NET Core Web API project.

    Step 1. Install the following packages in your project.

    • Serilog
    • Serilog.AspNetCore
    • Serilog.Sinks.File

    After the installation of the necessary packages, we will need to configure Serilog in the appsetting.json file. So, in the appsetting.json file, we will add the code below for the Serilog configuration.

    "Serilog": {
        "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
        "MinimumLevel": {
          "Default": "Information",
          "Override": {
            "Microsoft": "Warning",
            "System": "Warning"
          }
        },
        "WriteTo": [
          { "Name": "Console" },
          {
            "Name": "File",
            "Args": {
              "path": "logs/log-.log",
              "rollingInterval": "Day",
              "rollOnFileSizeLimit": true
            }
          }
        ]
      },

    Step 2. In the Program.cs we will add the Serilog configuration:

    builder.Host.UseSerilog((context, configuration) =>
        configuration.ReadFrom.Configuration(context.Configuration));

    Step 3. Then, above the App.Run() write Serilog middleware

    app.UseSerilogRequestLogging();

    Step 4. Then, we can now log in to any C# class.

    Below is an example of logging in WeatherForecastController.

    private readonly ILogger<WeatherForecastController> _logger;
    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }
      [HttpGet(Name = "GetWeatherForecast")]
      public IEnumerable<WeatherForecast> Get()
      {
          _logger.LogInformation("Get Weather forecast called sucessfully");
    
          return Enumerable.Range(1, 5).Select(index => new WeatherForecast
          {
              Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
              TemperatureC = Random.Shared.Next(-20, 55),
              Summary = Summaries[Random.Shared.Next(Summaries.Length)]
          })
          .ToArray();
      }

    Now, let’s run the app and check. When you run the app and call the GetWeatherForecast endpoint of your Api, the log will be captured inside the log folder, and you can open the folder and see the log, which will look like the below one.

    Conclusion

    An extensive introduction to Serilog, a potent logging package for.NET applications, has been given in this post. We went through its benefits, such as structured logging, and showed you how to use it in an ASP.NET Core 8 application. Developers can get more comprehensive and helpful log data by integrating Serilog, which enhances system maintenance, monitoring, and troubleshooting.

    Serilog's structured logging feature improves log analysis and visualization, making it a vital tool for contemporary applications. Observability, dependability, and general health of your application can all be much improved by implementing Serilog.

    Windows Hosting Recommendation

    HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 8.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
     
    https://hostforlifeasp.net/

    Read More

    Best ASP.NET Core 8.0.7 Hosting in Europe

    Leave a Comment
    Based on its useful features and easy to use, many developer need powerful web hosting to support their ASP.NET Core 8.0.7 site well. Because of that, we will inform you the Best ASP.NET Core 8.0.7 Hosting in Europe provider with affordable price and high quality support. After reviewed 20+ ASP.NET Core 8.0.7 Hosting in Europe, we had come out with the best ASP.NET Core 8.0.7 Hosting in Europe, control libraries, databases, technical support, and web hosting price. 


    ASP.NET Core is a free and open-source web framework, and higher performance than ASP.NET, developed by Microsoft and the community. It is a modular framework that runs on both the full .NET Framework, on Windows, and the cross-platform .NET Core. Despite being a new framework, built on a new web stack, it does have a high degree of concept compatibility with ASP.NET MVC. ASP.NET Core applications supports side by side versioning in which different applications, running on the same machine, can target different versions of ASP.NET Core. This is not possible with previous versions of ASP.NET.

    Best & Cheap ASP.NET Core 8.0.7 Hosting in Europe

    Our Best, Cheap ASP.NET Core 8.0.7 Hosting in Europe Recommendation goes to HostForLIFEASP.NET, a leading web hosts who is well-known for offering high quality Windows hosting from shared hosting

    http://hostforlifeasp.net/European-ASPNET-Core-2-Hosting

    Founded in United Kingdom, and with years’ expansion, HostForLIFEASP.NET has grown into one of top 10 ASP.NET Core 8.0.7 Hosting in Europe hosting providers for offers reliable and affordable web hosting services on Windows platforms. HostForLIFEASP.NET a worldwide provider of hosting support the latest release of Microsoft's widely-used ASP.NET Core 8.0.7 Hosting in Europe. You can take advantage of the powerful ASP.NET Core 8.0.7 Hosting in Europe technology in all Windows Shared Hosting, Windows Reseller Hosting and Windows Cloud Hosting Packages. 

    SALE 35% OFF NOW!

    HostForLIFEASP.NET Budget Friendly Price – The service includes 4 packages called as HostForLIFE Basic, Budget, Economy and Business with the price starting at Є2.97/mo.


    • 30 Days Money Back Guarantee – This means webmasters are allowed to get a refund if they cancel the services because of dissatisfaction within the first 30 days.
    • Satisfactory Uptime – HostForLIFEASP.NET employs state-of-the-art data centers and advanced technologies guaranteeing 99.99% uptime shown by the following chart.

    HostForLIFE ASP.NET Core 8.0.7 Hosting in Europe Performance

    HostForLIFEASP.NET ASP.NET Core 8.0.7 web host reliability is absolutely outstanding compared to other comprehensive web hosting companies. HostForLIFEASP.NET is managed by a sophisticated team with lots of Windows server experts. With the correct IIS, website and file system permission configuration, the security of the hosting websites is well isolated. That means, when one website is hacked by improper code, it’s rare opportunity for other websites be affected.

    Technical Support

    As introduced above, HostForLIFEASP.NET has an experienced team on supporting ASP.NET and ASP.NET Core 8.0.7 Hosting in Europe. All of their technical support staffs are kindly, sophisticated and knowledgeable on either Windows platform or SQL Server 2016 databases. HostForLIFEASP.NET provides 24/7 email and ticket system support mainly. Based on our testing, the average of the first response is about 30 minutes, and it could be faster in working time. HostForLIFEASP.NET guarantees to respond each support ticket in 12 hours.

    HostForLIFE is Best Option for ASP.NET Core 8.0.7 Hosting in Europe

    Frankly speaking, HostForLIFE is best option to host your ASP.NET Core 8.0.7 Hosting in Europe. You just need to spend €2.97/month to host your site with them and you can install the latest ASP.NET Core 8.0.7 via their Plesk control panel. We would highly recommend them as your ASP.NET Core 8.0.7 Hosting in Europe.

    http://hostforlifeasp.net/European-ASPNET-Core-2-Hosting

    Read More

    How to Create a Custom Middleware Component in ASP.NET Core?

    Leave a Comment

    With the help of the robust ASP.NET Core middleware, developers may implement unique logic to handle incoming requests and outgoing responses, allowing them to personalize the request pipeline. Each middleware component has the option to handle the request or forward it to the following component in the pipeline. These components are run in a particular order.



    An example of a custom middleware component in ASP.NET Core is shown.

    public class LoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<LoggingMiddleware> _logger;
    
        public LoggingMiddleware(RequestDelegate next, ILogger<LoggingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }
    
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                // Log the request details
                _logger.LogInformation($"Request: {context.Request.Method} {context.Request.Path}");
    
                // Call the next middleware in the pipeline
                await _next(context);
            }
            catch (Exception ex)
            {
                // Log the exception
                _logger.LogError(ex, "An error occurred while processing the request.");
                throw;
            }
            finally
            {
                // Log the response details
                _logger.LogInformation($"Response: {context.Response.StatusCode}");
            }
        }
    }

    In this example, we create a LoggingMiddleware class that logs the request and response details to the console. The InvokeAsync method is the entry point for the middleware component. It receives an HttpContext object, which represents the current HTTP request and response.

    Inside the InvokeAsync method, we first log the request details using the ILogger instance. Then, we call the _next delegate, which invokes the next middleware component in the pipeline. After the next middleware component has been completed, we log the response details.

    To register the custom middleware component in the application's request pipeline, you can use the UseMiddleware extension method in the Startup.Configure method.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Other middleware components...
    
        app.UseMiddleware<LoggingMiddleware>();
    
        // Other middleware components...
    }

    This will add the LoggingMiddleware component to the request pipeline, and it will be executed for every incoming request.

    Middleware components can be used for various purposes, such as logging, authentication, caching, compression, and more. ASP.NET Core also provides several built-in middleware components that you can use out of the box, such as UseStaticFiles, UseRouting, UseEndpoints, and UseAuthentication.

    Windows Hosting Recommendation

    HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2012 R2, SQL Server 2014, ASP.NET 7.0.4, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
     
    https://hostforlifeasp.net/
     
    Read More
    Previous PostOlder Posts Home